package jgl.vajra.kingkong.part.vehicle.activity;

import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.OnLinePayBean;
import jgl.vajra.kingkong.databinding.ActivityImmediatePaymentBinding;
import jgl.vajra.kingkong.event.CityChoiceEvent;
import jgl.vajra.kingkong.event.PayStatusEvent;
import jgl.vajra.kingkong.event.PaymentSuccessEvent;
import jgl.vajra.kingkong.event.WorkingFieldEvent;
import jgl.vajra.kingkong.manager.AccountManager;
import jgl.vajra.kingkong.manager.PayManager;
import jgl.vajra.kingkong.part.vehicle.contract.ImmediatePaymentContract;
import jgl.vajra.kingkong.part.vehicle.viewModel.ImmediatePaymentViewModel;
import jgl.vajra.kingkong.widget.manager.RxJavaHttpManager;
import jgl.vajra.kingkong.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;

@CreateViewModel(ImmediatePaymentViewModel.class)
public class ImmediatePaymentActivity extends BaseMVVMActivity<ImmediatePaymentViewModel, ActivityImmediatePaymentBinding> implements ImmediatePaymentContract.View {

    private String newBalance;
    private String amount;
    private String orderId;
    private String authorization;

    private int payType = 0; //0余额  1支付宝支付  3微信支付
    private int overtime;//overtime 1-订单支付，2-延时支付

    @Override
    public int getLayoutId() {
        return R.layout.activity_immediate_payment;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);
        authorization = AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization;

        orderId = getIntent().getStringExtra("orderId");
        amount = getIntent().getStringExtra("amount");
        overtime = getIntent().getIntExtra("overtime", 0);
        mBinding.tvDetermine.setText("余额支付¥" + amount);
        mBinding.tvAmount.setText(amount);

        if (overtime == 1) {
            mBinding.tvContent.setText("给钱后机佬立即赶往干活地，如单子取消，预\n付款将立即原路径退回");
        } else if (overtime == 2) {
            mBinding.tvContent.setText("给钱后机佬立即继续干活，单子确定后将不能\n取消订单");
        }

        mBinding.iv1.setSelected(true);
        requestNetData();
    }

    private void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        mViewModel.getAccountBalanceData(map);
    }


    @Override
    public void onDetermine() {
        if (payType == 0) {//余额支付
           /* Map<String, Object> map = new HashMap<>();
            map.put("Authorization", authorization);
            map.put("orderId", AEACCoder.encrypt(orderId + "&&" + amount));
            Logger.d(orderId + "===" + amount + "订单号==  :" + AEACCoder.encrypt(orderId + "&&" + amount));
            mViewModel.determinePaymentData(map);*/

            PayManager.getInstance().payBalance(this, orderId, amount, overtime);
        } else if (payType == 1) {//支付宝支付
            PayManager.getInstance().payAli(this, orderId, amount, overtime);
        } else if (payType == 3) {//微信支付
            PayManager.getInstance().payWX(this, orderId, amount, overtime);
        }
    }

    @Override
    public void onAliPay() {
        payType = 1;
        mBinding.ivAliPay.setSelected(true);
        mBinding.ivWxPay.setSelected(false);
        mBinding.iv1.setSelected(false);
    }

    @Override
    public void onWXPay() {
        payType = 3;
        mBinding.ivWxPay.setSelected(true);
        mBinding.iv1.setSelected(false);
        mBinding.ivAliPay.setSelected(false);
    }

    @Override
    public void returnAccountBalanceData(String data) {
        String balance = AEACCoder.decrypt(data);
        //截取&前面的约
        newBalance = balance.substring(0, balance.indexOf("&"));

        mBinding.tvBalance.setText("可用余额" + newBalance + "元");
    }

    //余额支付
    @Override
    public void onBalancePayment(int type) {
        payType = 0;
        switch (type) {
            case 1:
                mBinding.tvDetermine.setText("余额支付¥" + amount);
                mBinding.iv1.setSelected(true);
                mBinding.ivWxPay.setSelected(false);
                mBinding.ivAliPay.setSelected(false);
                break;
        }

    }

    @Override
    public void returnDeterminePaymentData() {
        ToastUtils.showShort("支付成功");
        EventBus.getDefault().post(new PaymentSuccessEvent());
        finish();
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayStatusEvent(PayStatusEvent event) {
        int statusType;
        if (event.status) {
            statusType = 1;
        } else {
            statusType = 2;
        }

        //微信支付成功或者失败回调,并调用后台接口
        Map<String, Object> map = new HashMap<>();
        map.put("authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("orderId", AEACCoder.encrypt(orderId + "&&" + statusType));
        map.put("tag", event.tag);//tag=2并支付成功时：orderId=AES加密(订单号 + "&&" + 1)，tag=2并支付失败时：orderId=AES加密(订单号 + "&&" + 2
        map.put("overtime", overtime);
        RetrofitJsonManager.getInstance().getApiService().payWxCallback(map)
                .compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(false, null) {
                    @Override
                    public void _onNext(String wxPayBean) {
                        if (event.status) {
                            EventBus.getDefault().post(new PaymentSuccessEvent());
                            finish();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        super._onError(errorMessage, errorCode);
                        if (event.status) {
                            EventBus.getDefault().post(new PaymentSuccessEvent());
                            finish();
                        }
                    }
                });
    }
}
